<?php
namespace Home\Controller;

use Think\Controller;
use Home\Controller\PublicController;
header('Content-type:text/html;charset=utf-8');

class UserController extends PublicController
{
    //通过session获取用户id   供其他方法调用
    public function getUserId()
    {
        $user_id=I('session.user_id');
        if(!$user_id){
            redirect(U('Index/login'));
        }else{
            return $user_id;
        }
    }

    //个人中心首页
    public function index()
    {
        //---导航信息
        $this->navigation1();
        //---导航信息
        $user_id = $this->getUserId();     //通过session获取用户id
        $order=M('Orders');
        //待处理订单数量
        $wait_orders_num=$order->where("status=0 OR status=2")->count();
        //获取该用户的已收货订单且未评论的商品详情的数据
        $evaluate_goods_num=$order->where(array('think_orders.uid'=>$user_id,'think_orders.status'=>3,'think_detail.status'=>0))->join("think_detail ON think_detail.order_id=think_orders.id")->count();
        $this->assign('wait_orders_num',$wait_orders_num);
        $this->assign('evaluate_goods_num',$evaluate_goods_num);
        $this->display('User/Mydr/index');
    }

    //我的订单
    public function order()
    {//---导航信息
        $this->navigation1();
        //---导航信息
        $user_id = $this->getUserId();     //通过session获取用户id
        $orders_data = M('Orders')->where(array('think_orders.uid' => $user_id))->order('status,addtime desc')->select();
        $this->assign('orders_data', $orders_data);
        $this->display('User/Myorder/order');
    }

    //订单详情
    public function orderDetail()
    {
        //---导航信息
        $this->navigation1();
        //---导航信息
        $user_id = $this->getUserId();     //通过session获取用户id
        $order_id = I('get.orderid');
        $order_data = M('Orders')->where(array('uid' => $user_id))->find($order_id);
        $order_detail_data = M('Orders')->where(array('think_orders.uid' => $user_id, 'think_orders.id' => $order_id))->join("think_detail ON think_orders.id=think_detail.order_id")->join("think_goods_detail ON think_detail.goods_detail_id=think_goods_detail.id")->join("think_goods ON think_goods.id=think_goods_detail.goods_id")->join("think_type ON think_goods.type_id=think_type.id")->select();
        //dump($order_detail_data);die;
        $this->assign('order_data', $order_data);
        $this->assign('order_detail_data', $order_detail_data);
        $this->display('User/Myorder/orderDetail');
    }

    //去付款
    public function topay()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $order_id = I('get.orderid');
        $order_data = M('Orders')->where(array('uid' => $user_id, 'id' => $order_id))->Field('total,status')->find();
        //判断订单状态是否为 未付款 不是则跳转到订单页
        if ($order_data['status'] != 0) {
            //重定向，跳转
            $this->redirect('order', 0);
        }
        $this->assign('order_id', $order_id);
        $this->assign('total', $order_data['total']);
        $this->display('User/Myorder/topay');
    }

    //付款操作
    public function topayAction()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $order_id = I('post.order_id');
        $res = M('Orders')->where(array('uid' => $user_id, 'id' => $order_id))->setField('status', 1);
        if ($res) {
            $data['status'] = 1;
            $data['content'] = '支付成功，期盼你的下次光临';
        } else {
            $data['status'] = -1;
            $data['content'] = '支付失败，请重试！';
        }
        $this->ajaxReturn($data);
    }

    //取消订单
    public function cancelOrder()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $order_id = I('post.order_id');
        $orders=M('Orders');
        $res = $orders->where(array('uid' => $user_id, 'id' => $order_id))->setField('status', 4);
        if ($res) {
            $order_detail_data=$orders->where(array('think_orders.id'=>$order_id))->join("think_detail ON think_orders.id=think_detail.order_id")->select();
            $goods=M('Goods');
            foreach($order_detail_data as $v){
                //更改商品的库存和销量
                $goods->where(array('id'=>$v['goods_id']))->setInc('total_stock',$v['num']);
                $goods->where(array('id'=>$v['goods_id']))->setDec('sales',$v['num']);
                //更改商品详情的库存
                M('Goods_detail')->where(array('id'=>$v['goods_detail_id']))->setInc('stock',$v['num']);
            }
            $data['status'] = 1;
            $data['content'] = '退订成功，欢迎你的下次光临';
        } else {
            $data['status'] = -1;
            $data['content'] = '退订失败，请重试！';
        }
        $this->ajaxReturn($data);
    }

    //确认收货
    public function confirmReceipt()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $order_id = I('post.order_id');
        $res = M('Orders')->where(array('uid' => $user_id, 'id' => $order_id))->setField('status', 3);
        if ($res) {
            $data['status'] = 1;
            $data['content'] = '确认成功，欢迎你的下次光临';
        } else {
            $data['status'] = -1;
            $data['content'] = '确认失败，请重试！';
        }
        $this->ajaxReturn($data);
    }

    //我的评价
    public function evaluate()
    {
        //---导航信息
        $this->navigation1();
        //---导航信息
        $user_id = $this->getUserId();     //通过session获取用户id
        //获取该用户的已收货订单且未评论的商品详情的数据
        $order_goods=M('Orders')->where(array('think_orders.uid'=>$user_id,'think_orders.status'=>3,'think_detail.status'=>0))->join("think_detail ON think_detail.order_id=think_orders.id")->order('think_orders.addtime desc')->select();
        //dump($order_goods);die;
        $this->assign('order_goods',$order_goods);
        $this->display('User/Myorder/evaluate');
    }
    //----屏蔽关键字
    public function Filter_word($str)
    {
        $words = "java|JAVA|赌博|毒品|人口贩子|wtf|WTF|政府|中国共产党";
        $matched = preg_replace('/'.$words.'/i', '***', $str);
        return $matched;
    }
    //评价编辑页 弹窗调用
    public function evaluate_edit(){
        $user_id = $this->getUserId();     //通过session获取用户id
        if(IS_POST){
            $order_detail_id=I('post.order_detail_id');
            $goods_id=I('post.goods_id');
            //获取评论的状态 0，新评论 1，追加评论
            $evaluate_status=I('post.status');
            //$goods_detail_id=I('post.goods_detail_id');
            //做关键字屏蔽处理
            $content=$this->Filter_word(I('post.content'));
            $res=M('News')->add(array('users_id'=>$user_id,'order_detail_id'=>$order_detail_id,'goods_id'=>$goods_id,'content'=>$content));
            if($evaluate_status==0){
                if($res){
                    $res_1=M('Detail')->where(array('id'=>$order_detail_id))->setField('status',1);
                    if($res_1){
                        $data['status']=1;
                        $data['content']='评论成功';
                    }else{
                        $data['status']=0;
                        $data['content']='评论失败，请重试';
                        M('News')->delete($res);
                    }
                }else{
                    $data['status']=-1;
                    $data['content']='评论失败，请重试';
                }
            }else{
                if($res){
                    $data['status']=1;
                    $data['content']='追加成功';
                }else{
                    $data['status']=-2;
                    $data['content']='追加失败，请重试';
                }
            }
            $this->ajaxReturn($data);
        }
        $this->display('User/Myorder/evaluate_edit');
    }
    //已评论的商品  ajax获取数据
    public function doneEvaluate()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $order_goods=M('Orders')->join("think_detail ON think_detail.order_id=think_orders.id")->where(array('think_orders.uid'=>$user_id,'think_orders.status'=>3,'think_detail.status'=>1))->order('think_orders.addtime desc')->select();
        if($order_goods){
            $news=M('News');
            $str='';
            foreach($order_goods as $v){
                $str.="<tr><td>{$v['order_id']}</td><td><a href='../Goods/details/id/{$v['goods_detail_id']}'>{$v['goods_style']}{$v['goods_name']}</a></td><td>{$v['addtime']}</td><td></td></tr>";
                $evaluate_content=$news->where(array('users_id'=>$user_id,'order_detail_id'=>$v['id']))->select();
                if($evaluate_content){
                    foreach($evaluate_content as $c){
                        if(count($evaluate_content)==1){
                            $str.="<tr class='evaluste_content'><td></td><td>评论时间<br/>{$c['addtime']}</td><td>{$c['content']}</td><td><a href='javascript:addEvaluate({$c['order_detail_id']},{$c['goods_id']},1)'>追加评论</a></td></tr>";
                        }else{
                            $str.="<tr class='evaluste_content'><td></td><td>评论时间<br/>{$c['addtime']}</td><td>{$c['content']}</td><td></td></tr>";
                        }
                    }
                }else{
                    $data['status']=-1;
                    $data['content']='<tr><td colspan="5">没有评论的商品，去评论吧！</td></tr>';
                }
            }
            $data['status']=1;
            $data['content']=$str;
        }else{
            $data['status']=-2;
            $data['content']='<tr><td colspan="5">没有评论的商品，去评论吧！</td></tr>';
        }
        /*dump($order_goods);die;
        $evaluate=M('News')->where(array('think_news.users_id'=>$user_id))->join("think_detail ON think_news.order_detail_id=think_detail.id")->order('think_news.addtime desc')->select();
        //dump($evaluate);die;
        if($evaluate){
            $data['status']=1;
            $str='';
            foreach($evaluate as $v){
                $str.="<tr><td>{$v['order_id']}</td><td><a href='../Goods/details/id/{$v['goods_detail_id']}'>{$v['goods_style']}{$v['goods_name']}</a></td><td>{$v['content']}</td><td>{$v['addtime']}</td><td><a href='javascript:addEvaluate({$v['order_detail_id']},{$v['goods_id']},1)'>追加评论</a></td></tr>";
            }
            $data['content']=$str;
        }else{
            $data['status']=-1;
            $data['content']='<tr><td colspan="5">没有评论的商品，去评论吧！</td></tr>';
        }*/
        $this->ajaxReturn($data);
    }

    //我的购物车
    public function cart()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $cart = M('Cart');
        $cart_data = $cart->where(array('uid' => $user_id))->select();
        if (IS_POST) {
            //做购物车中商品数量增减处理
            $data = I('post.');
            $res = $cart->save($data);
        }
        $this->assign('cart_data', $cart_data);
        $this->display('User/Myorder/cart');
    }

    //删除购物车中的商品
    public function delCart()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $cart_id = I('post.cart_id');
        $res = M('Cart')->where(array('uid' => $user_id))->delete($cart_id);
        if ($res) {
            $data['status'] = 1;
            $data['content'] = '清空成功';
        } else {
            $data['status'] = -1;
            $data['content'] = '清空失败，请重试';
        }
        $this->ajaxReturn($data);
    }

    //清空购物车
    public function clearCart()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $res = M('Cart')->where(array('uid' => $user_id))->delete();
        if ($res) {
            $data['status'] = 1;
            $data['content'] = '清空成功';
        } else {
            $data['status'] = -1;
            $data['content'] = '清空失败，请重试';
        }
        $this->ajaxReturn($data);
    }

    //真爱协议
    public function loveAgreement()
    {
        //---导航信息
        $this->navigation1();
        //---导航信息
        $this->display('User/Myorder/loveAgreement');
    }

    //确认订单页获取默认收货地址操作
    public function orderAddressAction()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $address=M('Shipping_address');
        if(I('post.action')=='getDefaultAddress'){
            $defalutAddress=$address->where(array('uid'=>$user_id,'status'=>1))->find();
            //判断是否有默认收货地址
            if($defalutAddress){
                $data['status']=1;
                $data['content']=$defalutAddress;
            }else{
                $data['status']=-1;
                $data['content']='没有设置默认地址，请选择或填写收货地址。';
            }
            $this->ajaxReturn($data);
        }
        if(I('post.action')=='getOtherAddress'){
            $otherAddress=$address->where(array('uid'=>$user_id,'status'=>2))->order('addtime desc')->select();
            if($otherAddress){
                $data['status']=1;
                $content='';
                foreach($otherAddress as $v){
                    $content.="<tr><td><input value='{$v['id']}' name='address' type='radio' onclick='otherAddress({$v['id']})'></td><td class='name'>{$v['name']}</td><td class='address'>{$v['province']}{$v['city']}{$v['district']}{$v['street']}</td><td class='mobile'>{$v['mobile']}</td><td class='postcode'>{$v['postcode']}</td></tr>";
                }
                $data['content']=$content;
            }else{
                $data['status']=-1;
                $data['content']='<tr><td colspan="5">没有其他收货地址，请使用默认地址或添加新地址</td></tr>';
            }
            $this->ajaxReturn($data);
        }
    }
    //确认订单 填写地址
    public function sureOrder()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $address = M('Shipping_address');
        $default_address = $address->where(array('status' => 1, 'uid' => $user_id))->find();
        if ($default_address) {
           // $this->assign('default_address', $default_address);
        }
        $other_address = $address->where(array('status' => 2, 'uid' => $user_id))->select();
        $this->assign('other_address', $other_address);
        //获取选择的商品的信息
        $checked_cart_id = I('post.checked');       //获取选择的要购买的商品在购物车中的id串  例：1,4,6
        $cart = M('Cart');
        $checked_data = $cart->where(array('id' => array('in', $checked_cart_id)))->select();
        $this->assign('checked_data', $checked_data);
        $this->display('User/Myorder/sureOrder');
    }

    //提交订单 支付
    public function submitOrder()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $shipping_address_id = I('post.address');     //获取收货地址的id
        $ckecked_cart_id = I('post.checked_cart_id');     //获取选取商品在购物车中的id
        $order_note = I('post.ordernote');
        $shipping_address_data = M('Shipping_address')->where(array('uid' => $user_id))->find($shipping_address_id);
        //获取购物车中对应商品详情信息
        $ckecked_goods_data = M('Cart')->where(array('think_cart.uid' => $user_id, 'think_cart.id' => array('in', $ckecked_cart_id)))->join("think_goods_detail ON think_cart.goods_detail_id=think_goods_detail.id")->select();
        $total = 0;       //商品总价
        foreach ($ckecked_goods_data as $v) {
            $total += $v['price'] * $v['num'];
        }
        //获取订单信息
        $order_data['uid'] = $user_id;
        $order_data['linkman'] = $shipping_address_data['name'];
        $order_data['address'] = $shipping_address_data['province'] . $shipping_address_data['city'] . $shipping_address_data['district'] . $shipping_address_data['street'];
        $order_data['code'] = $shipping_address_data['postcode'];
        $order_data['phone'] = $shipping_address_data['mobile'];
        $order_data['note'] = $order_note;
        $order_data['total'] = $total;
        $order_id = M('Orders')->add($order_data);    //添加订单，并返回的生成订单的id
        if ($order_id) {
            //写入信息到订单详情
            $tag = 0;     //判断订单详情添加成功的标志
            $goods=M('Goods');
            foreach ($ckecked_goods_data as $v) {
                $order_detail['order_id'] = $order_id;
                $order_detail['goods_id'] = $v['goods_id'];
                $order_detail['goods_detail_id'] = $v['goods_detail_id'];
                $order_detail['goods_name'] = $v['goods_name'];
                $order_detail['goods_style'] = $v['goods_style'];
                $order_detail['material'] = $v['material'];
                $order_detail['size'] = $v['size'];
                $order_detail['carve'] = $v['carve'];
                $order_detail['price'] = $v['price'];
                $order_detail['num'] = $v['num'];
                $res = M('Detail')->add($order_detail);
                //更改商品的库存和销量
                $goods->where(array('id'=>$order_detail['goods_id']))->setDec('total_stock',$order_detail['num']);
                $goods->where(array('id'=>$order_detail['goods_id']))->setInc('sales',$order_detail['num']);
                //更改商品详情的库存
                M('Goods_detail')->where(array('id'=>$order_detail['goods_detail_id']))->setDec('stock',$order_detail['num']);
                if (!$res) {
                    $tag++;
                }
            }
            //添加订单详情成功则删除购物车中已提交的商品
            //否则会删除生成的订单，让用户重新提交
            if ($tag == 0) {
                //删除购物车中的商品
                M('Cart')->where(array('uid' => $user_id, 'id' => array('in', $ckecked_cart_id)))->delete();
            } else {
                M('Orders')->where(array('uid' => $user_id, 'id' => $order_id))->delete();
                $this->error('添加订单详情失败', U('cart'));
            }

        } else {
            $this->error('添加订单失败', U('cart'));
        }
        $this->assign('order_id', $order_id);
        $this->assign('total', $total);
        $this->display('User/Myorder/submitOrder');
    }

    //收藏
    public function myFavorites()
    {
        //---导航信息
        $this->navigation1();
        //---导航信息
        $this->display('User/Myorder/myFavorites');
    }

    //预约
    public function appointment()
    {
        //---导航信息
        $this->navigation1();
        //---导航信息
        $this->display('User/Myorder/appointment');
    }

    //个人信息修改页
    public function personInfo(){
        //---导航信息
        $this->navigation1();
        //---导航信息
        $m=M('users');
        $b=$_SESSION['user_id'];
        //dump($b);
        $result=$m->where('id='.$b)->select();
        $this->assign('result',$result);
        /*dump($result);*/
        $this->display('User/Mydr/personInfo');
    }
    //个人信息修改
    public function personInfo_change(){
        $m=M('users');
        $b=$_SESSION['user_id'];
        $data['tel']=I('post.tel');
        $data['code']=I('post.code');
        $data['email']=I('post.email');
        $data['truename']=I('post.truename');
        $data['sex']=I('post.sex');
        $data['id_card']=I('id_card');
        $data['address']=I('post.location_p').'-'.I('post.location_c').'-'.I('post.location_a').'--';
        $data['d_address']=I('d_address');
        $res=$m->where('id='.$b)->save($data);

        if($res){
            $this->success('修改成功');
        }else{
            $this->success('修改失败');
        }
         dump($data);
    
    }
    //密码修改页
    public function mypwd(){
        //---导航信息
        $this->navigation1();
        //---导航信息
        $m=M('users');
        $b=$_SESSION['user_id'];
        $result=$m->where('id='.$b)->find();
        $this->display('User/Mydr/mypwd');
    }
    //密码修改
    public function password_change(){

        $m=M('users');
        $data['id']=$_SESSION['user_id'];
        $data['password']=I('post.password');//判断该用户密码是否存在
        $data['new1']=I('post.new_password');//新密码
        $data['new2']=I('post.new_password2');//确认新密码
        $res=$m->where($data)->find();
        if($res){
                if($data['new1']===$data['new2']){//新密码不能为空由validate判断
                    $m->where('id='.$data['id'])->save($new_data);
                }else{
                }
        }else{
            $a='原密码错误！请重新输入！';
            $this->assign('a',$a);//echo "原密码错误";
            // $arr=$m->getLastSql();//获取最后一次的sql语句
            // echo $arr; 
            $this->display('User/Mydr/mypwd');
         }

    }
    //三级联动省区县
    public function address()
    {
        //调取三级联动数据表
        if (IS_POST) {
            //三级联动的省级数据
            if (I('post.action')) {
                $province = M('Province')->select();
                $str = '';
                foreach ($province as $v) {
                    $str .= '<option value="' . $v['provinceid'] . '">' . $v['province'] . '</option>';
                }
                $this->ajaxReturn($str);
            }
            //三级联动的市级数据
            if (I('post.provinceid')) {
                $provinceid = I('post.provinceid');
                $city = M('City')->where(array('fatherid' => $provinceid))->select();
                $str = '';
                foreach ($city as $v) {
                    $str .= '<option value="' . $v['cityid'] . '">' . $v['city'] . '</option>';
                }
                $this->ajaxReturn($str);
            }
            //三级联动的县级数据
            if (I('post.cityid')) {
                $cityid = I('post.cityid');
                $area = M('Area')->where(array('fatherid' => $cityid))->select();
                $str = '';
                foreach ($area as $v) {
                    $str .= '<option value="' . $v['areaid'] . '">' . $v['area'] . '</option>';
                }
                $this->ajaxReturn($str);
            }
        }
    }

    //收货地址页面
    public function myAddress()
    {
        //---导航信息
        $this->navigation1();
        //---导航信息
        $user_id = $this->getUserId();     //通过session获取用户id
        $address = M('Shipping_address');
        if (IS_POST) {
            //添加地址操作
            $msg = I('post.');
            $msg['uid'] = $user_id;
            //判断是否设置为默认收货地址     且每个用户只能有一个默认收货地址
            if ($msg['status'] == 1) {
                $address->where(array('status' => 1))->setField('status', 2);
            }
            $res = $address->add($msg);
            if ($res) {
                $data['status'] = 1;
                $data['content'] = '添加成功';
                $data['address_id']=$res;
            } else {
                $data['status'] = -1;
                $data['content'] = '添加地址失败,请重试';
            }
            $this->ajaxReturn($data);
        }
        //获取个人的收货地址，并根据是否为默认地址和添加时间排序
        $address_data = $address->where(array('uid' => $user_id))->order('status,addtime desc')->select();
        $this->assign('address_data', $address_data);

        $this->display('User/Mydr/myAddress');
    }

    //设置默认收货地址
    public function setDefaultAddress()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $id = I('post.id');
        $address = M('Shipping_address');
        //将默认地址设为普通地址   不能对其判断，因有可能以前就没有默认地址
        $address->where(array('status' => 1, 'uid' => $user_id))->setField('status', 2);
        //设置默认地址
        $res = $address->where(array('id' => $id, 'uid' => $user_id))->setField('status', 1);
        if ($res) {
            $data['status'] = 1;
            $data['content'] = '设置成功';
        } else {
            $data['status'] = -1;
            $data['content'] = '设置失败，请重试！';
        }
        $this->ajaxReturn($data);
    }

    //删除收货地址操作
    public function deleteAddress()
    {
        $user_id = $this->getUserId();     //通过session获取用户id
        $id = I('post.id');
        $res = M('Shipping_address')->where(array('uid' => $user_id))->delete($id);
        if ($res) {
            $data['status'] = 1;
            $data['content'] = '删除成功';
        } else {
            $data['status'] = -1;
            $data['content'] = '删除失败，请重试！';
        }
        $this->ajaxReturn($data);
    }

    //纪念日
    public function mydr_jnr()
    {
        //---导航信息
        $this->navigation1();
        //---导航信息
        $this->display('User/Mydr/mydr_jnr');
    }

}
